package com.cian.service.impl;

import com.cian.entity.History;
import com.cian.entity.dto.StockDTO;
import com.cian.service.IRedis;
import com.cian.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
public class RedisImpl implements IRedis {
    @Autowired
    RedisUtils redisUtils;

    @Override
    public List<StockDTO> getStockByCode(String serverCode, int nextPage, int pageMaxNum) {
        // 获取Redis中的数组对应的长度
        Long len = redisUtils.lSize(serverCode);
        if(len == null) return null;
        long left = nextPage * pageMaxNum > len - pageMaxNum ? len - pageMaxNum: nextPage * pageMaxNum ;
        long right = left + pageMaxNum;
        List<StockDTO> list = new LinkedList<>();
        List<Object> items = redisUtils.lGet(serverCode, left, right);
        if(items == null) return null;
        items.forEach(item->{
            list.add((StockDTO) item); });
        // 判断是否为空，如果为空，表示Redis中不存在该项，则返回null
        if(list.isEmpty()) return null;
        return list;
    }

    @Override
    public StockDTO finderForCoId(String serverCode, int coId) {
        List<Object> list =  redisUtils.lGet(serverCode, 0, -1);
        if(list == null) return null;
        for (Object o : list) {
            if(((StockDTO)o).getCoId() == coId){
                return (StockDTO)o;
            }
        }
        return null;
    }

    @Override
    public boolean setHistory(String account, String serverCode, Date date, History history) {
        return redisUtils.hset(account, serverCode+date.toString(), history);
    }

    @Override
    public History getHistory(String account, String serverCode, Date date) {
        return (History) redisUtils.hget(account, serverCode+date.toString());
    }


    @Override
    public boolean setStockByCode(String serverCode, List<StockDTO> list, long timeout) {
        if(list == null) return false;
        try{
            // 清空对于的项
            redisUtils.lclear(serverCode);
            list.forEach(item ->{
                redisUtils.lSet(serverCode, item, timeout);
            });
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }



}
